package com.suzhouhe.util.interceptor;

import com.suzhouhe.util.request.RequestWrapper;
import com.suzhouhe.util.utils.IpUtil;
import com.suzhouhe.util.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * 请求打印日志拦截器
 *
 * @author suzhouhe
 * @date 2020-12-09 11:31
 **/
@Component
public class ControllerLogInterceptor implements HandlerInterceptor {

    private Logger log = LoggerFactory.getLogger(ControllerLogInterceptor.class);

    private static final String METHOD_GET = "GET";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) {
        RequestWrapper requestWrapper = new RequestWrapper(request);
        String body = requestWrapper.getBody();
        String method = request.getMethod();
        String ipAddr = IpUtil.getIpAddr(request);
        String uri = request.getRequestURI();

        log.info("request info: ip address:{},method:{},uri:{}", ipAddr, method, uri);
        Enumeration<String> headerNames = request.getHeaderNames();
        StringBuilder sb = new StringBuilder();
        while (headerNames.hasMoreElements()) {
            String element = headerNames.nextElement();
            String headerValue = request.getHeader(element);
            sb.append(element).append(":").append(headerValue).append(",");
        }
        if (StringUtils.isEmpty(sb.toString())) {
            log.info("request info: headers is null");
        } else {
            log.info("request info: headers:{{}}", sb.substring(0, sb.length() - 1));
        }

        if (METHOD_GET.equalsIgnoreCase(method)) {
            log.info("request info: params:{{}}", request.getQueryString());
        } else {
            log.info("request info: params:{}", JsonUtil.beanToStr(body));
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
    }

}
